package ltd.sumfsy.grain.controller;

import ltd.sumfsy.grain.bean.User;
import ltd.sumfsy.grain.decorate.ResultData;
import ltd.sumfsy.grain.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * 登录控制器
 *
 * @author 范颂扬
 * @create 2021-07-06 16:46
 */
@RestController
public class LoginController {

    private UserService userService;

    @Autowired
    public LoginController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 用户登录
     *
     * @param username 用户名或电话号码
     * @param password 密码
     * @return ltd.sumfsy.grain.decorate.ResultData
     * @author 范颂扬
     * @date 2021-06-10 19:52
     */
    @PostMapping("/login")
    public ResultData login(@RequestParam("username") String username
            , @RequestParam("password") String password, HttpSession session) {
        // 将密码加密后进行对比（MD5 加密）
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        User user = new User().setUsername(username).setPassword(pwd);
        // 验证用户名和密码
        boolean res = userService.isExistForLogin(user);
        if (!res) {
            user.setUsername(null).setTelephone(username);
            // 验证电话号码和密码
            boolean res2 = userService.isExistForLogin(user);
            if (res2) {
                User userData = userService.queryByTel(username);
                session.setAttribute("userData", userData);
                return ResultData.success().addExtend("userData", userData);
            } else {
                return ResultData.fail().setMessage("用户名或电话不存在，或者密码错误");
            }
        }
        User userData = userService.queryByName(username);
        session.setAttribute("userData", userData);
        return ResultData.success().addExtend("userData", userData);
    }

}
